package www.sofn.com.contrller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import www.sofn.com.domain.R;
import www.sofn.com.exception.BaseException;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public R handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
        return R.error("没有权限，请联系管理员授权");
    }

    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable e) {
        log.error("异常：{}", e);
        return R.error("未知错误：请查看日志");
    }

    @ExceptionHandler(BaseException.class)
    public R handleException(BaseException e) {
        log.error("异常：{}", e.getMessage());
        return R.error(e.getMessage());
    }

    @ExceptionHandler(ConversionFailedException.class)
    public R handleException(ConversionFailedException e) {
        log.error("异常：{}", e.getMessage());
        return R.error("参数传参异常");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        log.info("异常：{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        return R.error(bindingResult.getFieldError().getDefaultMessage());
    }


    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R handleException(HttpMessageNotReadableException e) {
        log.error("异常：{}", e.getMessage());
        return R.error("参数转换异常");
    }
}
